<script setup lang="ts">
 import {
    Edit,
    Delete,
    Plus
} from '@element-plus/icons-vue'
import { reactive, ref ,computed,onMounted} from 'vue'
import {reqAllCategory,reqAllCats,reqAddCat,reqUpdateCat,reqDeleteCat} from '@/api/catApi'
import { ElMessage, ElMessageBox } from 'element-plus'
// 存储所有猫咪的数据
const cats = ref([
  {
    id: 666,
    code:'00001',
    caption: 'Tom',
    category:'加菲猫',
    breedcode:'001',
    birth:'2022-10-05',
    height:0.16,
    gender:false
  },
  {
    id: 666,
    code:'00001',
    caption: 'Tom',
    category:'加菲猫',
    breedcode:'002',
    birth:'2022-10-05',
    height:0.16,
    gender:false
  }
])

let cat = ref({
  id: 0,
  code: '00001',
  caption: '波斯猫',
  breedCode: '002',
  birth: '2023-01-01',
  height: 0.36,
  gender: true
}) // 存储当前编辑的猫咪数据
let newRecord = ref(false) // 判断是否是新增记录
let breeds = ref([]) // 存储猫咪品种的选项数据
let breedsDic = computed(() => {
  //通过 computed 计算属性生成一个品种字典。
  // 它的键是品种的 code，值是品种的 caption。这个字典可以用来方便地根据品种代码显示品种名称。

  let data = {}

  for (let key in breeds.value) {
    let item = breeds.value[key]

    let obj = {}

    obj[item['code']] = item['caption']

    Object.assign(data, obj)
  }

  return data
})
const catForm: any = ref(null)
//对话框
const dialogFormVisible = ref(false)
const formLabelWidth = '140px'


const fetchCatData = async() => {
  const res = await reqAllCats()
  console.log(res.data.data)
  cats.value = res.data.data
}

const fetchBreedData = async() => {
  const res = await reqAllCategory()
  console.log(res.data.data)
  breeds.value = res.data.data
}
//校验规则  
const checkRules = {
  code: [
    { required: true, message: '不得为空' },

    { min: 5, max: 5, message: '须为5个字符' }
  ],

  caption: [
    { required: true, message: '不得为空' },

    { min: 1, max: 10, message: '不超过10个字' }
  ],

  breedCode: [{ required: true, message: '不得为空', trigger: 'change' }],

  birth: [{ required: true, message: '不得为空' }],

  height: [{ required: true, message: '不得为空' }]
}

onMounted(async () => {
  fetchBreedData() //获取所有猫咪品种的数据。

  fetchCatData() //获取所有猫咪的列表数据
})
const openDialog = () => {
  dialogFormVisible.value = true
  newRecord.value = true
  cat.value = {
    id: 0,
    code: '',
    caption: '',
    breedCode: '',
    birth: '2023-01-01',
    height: 0,
    gender: true
  }
}
//添加
const doAdd = () => {
  catForm.value.validate(async (valid: any) => {
    if (valid) {
      const res = await reqAddCat(cat.value)
      console.log(res.data.data)
      fetchCatData()
      //关闭对话框
      dialogFormVisible.value = false
    } else {
      return false
    }
  })

}

//保存
const doSave = () => {
  catForm.value.validate(async (valid: any) => {
    if (valid) {
      const res = await reqUpdateCat(cat.value)
      console.log(res.data.data)
      fetchCatData()
      //关闭对话框
      dialogFormVisible.value = false
    } else {
      return false
    }
  })
}

//删除
const doDelete = (row: any) => {
  ElMessageBox.confirm(`确实要删除 ${row.caption} 的数据么？`, '确认', {
    confirmButtonText: '确认',
    cancelButtonText: '取消'
  }).then(async () => {
    cat.value = row
    const res =await reqDeleteCat(cat.value.id)
    console.log(res.data.data)
    fetchCatData()
  })
}

//编辑
const doEdit = (row:any) => {
  console.log(row)
  cat.value = row
  dialogFormVisible.value = true
  newRecord.value = false
}

</script>

<template>
<h5>猫咪管理</h5>
<el-button type="success" :icon="Plus" @click="openDialog()">新增</el-button>
  <el-table :data="cats" stripe style="width: 100%">
    <el-table-column prop="id" label="ID" width="180" />
    <el-table-column prop="code" label="编号"/>
    <el-table-column prop="caption" label="名字" />
    <el-table-column prop="breedCode" label="品种">
      <template #default="scope">
        {{ breedsDic[scope.row.breedCode] }}
      </template>
    </el-table-column>
    <el-table-column prop="birth" label="生日" />
    <el-table-column prop="height" label="身长" />
    <el-table-column prop="gender" label="性别" />
         <el-table-column label="操作">
                <template #default="scope">
                    <el-button :icon="Edit" plain type="primary" @click="doEdit(scope.row)">修改</el-button>
                    <el-button :icon="Delete" plain type="danger" @click="doDelete(scope.row)">删除</el-button>                     
                </template>
            </el-table-column>
            <template #empty>
                <el-empty description="没有数据" />
            </template>
  </el-table>

<!-- 对话框 -->
<el-dialog v-model="dialogFormVisible" title="信息卡" width="850px" style="height: 200px">
    <el-form
      ref="catForm"
      :model="cat"
      :rules="checkRules"
      label-position="right"
      style="height: 170px"
    >
      <!-- 第一行: ID、编号、名字 -->
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="ID:">
            <el-input v-model="cat.id" readonly />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="编号:" prop="code">
            <el-input v-model="cat.code" minlength="5" maxlength="5" show-word-limit />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="名字:" prop="caption">
            <el-input
              v-model="cat.caption"
              minlength="1"
              maxlength="10"
              show-word-limit
              style="width: 362px"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 第二行: 性别、品种、生日、身长 -->
      <el-row :gutter="10">
        <el-col :span="6">
          <el-form-item label="性别:">
            <el-switch v-model="cat.gender" size="large" active-text="公猫" inactive-text="母猫" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="品种:" prop="breedCode">
            <el-select v-model="cat.breedCode" placeholder="请选择品种">
              <el-option
                v-for="(option, index) in breeds"
                :key="index"
                :value="option.code"
                :label="option.caption"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="生日:" prop="birth">
            <el-date-picker
              v-model="cat.birth"
              type="date"
              placeholder="请选择日期"
              value-format="YYYY-MM-DD"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="身长:" prop="height">
            <el-input-number
              v-model="cat.height"
              :precision="2"
              :step="0.01"
              :max="2"
              :min="0.01"
              style="width: 130px"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 按钮: 新增或保存 -->
      <el-row justify="end">
        <el-form-item>
          <el-button v-if="newRecord" type="success" @click="doAdd()">
            <el-icon><Plus /></el-icon> 新增
          </el-button>
          <el-button v-else type="primary" @click="doSave()">
            <el-icon><Edit /></el-icon> 保存
          </el-button>
        </el-form-item>
      </el-row>

    </el-form>
  </el-dialog>


</template>

<style scoped>

</style>
